package com.lkd.job;


import com.lkd.entity.UserEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.UserService;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.util.ShardingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 生成工单到缓存
 */
@Component
public class UserJob {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 每日工单量列表初始化
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) throws Exception{
        //todo:查询用户列表
        List<UserEntity> userEntities = userService.list();
        if (CollectionUtils.isEmpty(userEntities)){
            throw new LogicException("用户列表为空");
        }
        //todo:构建数据（zset）

        //任务如果没有传参数,则生成明天的初始数据
        LocalDate date = LocalDate.now().plusDays(1);
        //任务如果没有传参数,则生成今天的初始数据
        if ("today".equals(param)){
            date = LocalDate.now();
        }

        String dateStr = date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        //保存到每个用户任务到Zset
        for (UserEntity userEntity : userEntities) {
            //构造大key
            String key = "vmAutoTask." + dateStr + userEntity.getRegionId() + userEntity.getRoleCode();
            redisTemplate.opsForZSet().add(key,userEntity.getId(),0);
            //设置超时时间
            redisTemplate.expire(key,2, TimeUnit.DAYS);
        }

        return ReturnT.SUCCESS;
    }


}






























